﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using WpfSnqkGasAnalysis.Model;

using PdfSharpCore.Drawing;
using PdfSharpCore.Fonts;
using PdfSharpCore.Pdf;
using PdfSharpCore.Utils;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 打印预览
    /// </summary>
    /// 创建时间：2022-12-12 16:01:55。作者：王浩力
    public partial class WindowProofreadPrintPreview : Window
    {
        public WindowProofreadPrintPreview()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选中的数据
        /// </summary>
        /// 创建时间：2022-12-12 16:01:32 
        public Gas_analysis gas_Analysis = null;

        private delegate void LoadXpsMethod(FlowDocument flow);
        private readonly Object m_data;
        //private readonly FlowDocument m_doc;
        //private FlowDocument m_doc;
        private string _strTmplName;

        /// <summary>
        /// 打印文件，pdf
        /// </summary>
        private string pdfFileWork;

        public WindowProofreadPrintPreview(string strTmplName, Object data, IDocumentRenderer renderer = null)
        {
            InitializeComponent();
            m_data = data;
            _strTmplName = strTmplName;
            try
            {

                //m_doc = LoadDocumentAndRender(strTmplName, data, renderer);
                FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri("FlowDocumentPage\\" + strTmplName, UriKind.Relative));
                doc.PagePadding = new Thickness(70);
                doc.DataContext = data;

                //默认显示电子签名

                if (renderer != null)
                {
                    renderer.Render(doc, data);
                }

                Dispatcher.BeginInvoke(() =>
                {
                    LoadXps(doc);
                }, DispatcherPriority.Render);
            }
            catch (Exception ex)
            {
                var ex1 = ex.InnerException ?? ex;
                MessageBox.Show(ex1.Message,"错误",MessageBoxButton.OK,MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 用于DocumentViewer 预览，需要传入FlowDocument
        /// </summary>
        /// <param name="args"></param>
        /// 修改时间：2023-1-8 12:22:36。作者：王浩力
        public void LoadXpsOLD(FlowDocument args)
        {
            this.Height = 700;
            this.Width = 1000;
            this.docViewer.Visibility= Visibility.Visible;  


            /**   添加时间：2023-1-6 17:14:28。作者：王浩力
            如果文档中有图片，则鼠标悬浮在图片上之时触发异常：
            Entries cannot be opened multiple times in Update mode
            参考文档：
https://github.com/dotnet/runtime/issues/24962   
            
            IOException when viewing XpsDocument with DocumentViewer
https://github.com/dotnet/runtime/issues/39430

            DocumentViewer鼠标悬浮图片异常
            https://ask.csdn.net/questions/7502600
             */

            MemoryStream ms = new MemoryStream();
            try
            {
                //构造一个基于内存的xps document            
                Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
             
                //修改人：王浩力
                //Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");
                Uri uri = new Uri($"pack://{DateTime.Now.Ticks}.xps");

                //注释时间：2023-1-6 16:38:03
                //PackageStore.RemovePackage(uri);
                PackageStore.AddPackage(uri, package);

                //修改人：王浩力
                //XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);
                XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);

                //注释时间：2023-1-7 01:29:54
                ////修改时间：2023-1-7 01:03:32
                //string dir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "xps");
                //if (!System.IO.Directory.Exists(dir))
                //{
                //    System.IO.Directory.CreateDirectory(dir);
                //}
                //string xpsFilePath = System.IO.Path.Combine(dir, DateTime.Now.Ticks + ".xps");
                //XpsDocument xpsDocument = new XpsDocument(xpsFilePath, FileAccess.Write);

                //将flow document写入基于内存的xps document中去
                XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                writer.Write(((IDocumentPaginatorSource)args).DocumentPaginator);

                //获取这个基于内存的xps document的fixed document
                docViewer.Document = xpsDocument.GetFixedDocumentSequence();

                //关闭基于内存的xps document
                xpsDocument.Close();

                //package.Flush();
                //package.Close();
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("创建流文档异常", null, "WindowProofreadPrintPreview.LoadXps，异常：" + ex.Message);
            }
            finally
            {
                ms?.Close();
                ms?.Dispose();
            }
        }

        /// <summary>
        /// 直接用系统默认程序打开pdf
        /// </summary>
        /// <param name="args"></param>
        /// 创建时间：2023-1-8 12:23:09。作者：王浩力
        public void LoadXps(FlowDocument args)
        {
            /**   添加时间：2023-1-6 17:14:28。作者：王浩力
            如果文档中有图片，则鼠标悬浮在图片上之时触发异常：
            Entries cannot be opened multiple times in Update mode
            参考文档：
https://github.com/dotnet/runtime/issues/24962   
            
            IOException when viewing XpsDocument with DocumentViewer
https://github.com/dotnet/runtime/issues/39430

            DocumentViewer鼠标悬浮图片异常
            https://ask.csdn.net/questions/7502600
             */

            MemoryStream ms = new MemoryStream();
            try
            {
                //构造一个基于内存的xps document            
                Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
              
                //修改人：王浩力
                //Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");
                Uri uri = new Uri($"pack://{DateTime.Now.Ticks}.xps");

                //注释时间：2023-1-6 16:38:03
                //PackageStore.RemovePackage(uri);
                PackageStore.AddPackage(uri, package);


                //修改人：王浩力
                //XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);
                XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);
                 
                //将flow document写入基于内存的xps document中去
                XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                writer.Write(((IDocumentPaginatorSource)args).DocumentPaginator);
       
                string pdfDir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pdf");
                if (!System.IO.Directory.Exists(pdfDir))
                {
                    System.IO.Directory.CreateDirectory(pdfDir);
                }
                pdfFileWork = System.IO.Path.Combine(pdfDir, DateTime.Now.Ticks + ".pdf");
                //保存xps文档为pdf文件
                PdfSharp.Xps.XpsConverter.Convert(xpsDocument, pdfFileWork, 0);

                //打开文件，查看   //创建时间：2023-1-8 12:14:03。
                System.Diagnostics.Process.Start("explorer", pdfFileWork);

                //关闭基于内存的xps document
                xpsDocument.Close();

                //package.Flush();
                //package.Close();
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("创建流文档异常", null, "WindowProofreadPrintPreview.LoadXps，异常：" + ex.Message);
            }
            finally
            {
                ms?.Close();
                ms?.Dispose();
            }
        }


        //点击了 RadioButton
        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rad = (RadioButton)sender;
            if (docViewer == null)
            {
                e.Handled = true;
                return;
            }

            FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri("FlowDocumentPage\\" + _strTmplName, UriKind.Relative));
            doc.PagePadding = new Thickness(40);           
            doc.DataContext = m_data;
            doc.Tag = rad.Tag;   //1=显示签名;    0=不显示签名   

            //注释时间：2023-1-8 14:06:39。
            //SignNameShow(doc, e);

            Dispatcher.BeginInvoke(() =>
            {
                //LoadXpsOLD(doc);//测试

                LoadXps(doc); //正式
            }, DispatcherPriority.Render);
        }

        ///// <summary>
        ///// 电子签名显示处理
        ///// </summary>
       // //internal event EventHandler SignNameShow;

        ////执行打印
        //private void Print_Click(object sender, RoutedEventArgs e)
        //{
        //    //System.Diagnostics.Process.Start("explorer", pdfFileWork);
        //}
    }
}
